<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\MaterialInquiryModel;
use App\Models\MaterialModel;
use App\Models\WarehouseMaterialModel;
use App\Models\WarehouseMaterialRecordModel;
use App\Models\WarehouseModel;
use Illuminate\Http\Request;

class WorkbenchStorageController extends Controller
{
    //所有仓库
    public function warehouses()
    {
        return $this->return_data(WarehouseModel::where('company_id', 'like', '%"company_id":"' . auth('api')->user()->company_id . '"%')->get()->map(function ($item) {
            return ['id' => $item->id, 'name' => $item->warehouse_name];
        }));
    }

    //仓库对应材料列表
    public function materials(Request $request)
    {
        $request->validate(['orderBy_field' => 'in:stock,id,updated_at', 'orderBy_how' => 'in:ASC,DESC']);
        $keywords = $request->post('keywords');  //搜索关键词
        $warehouse_id = $request->post('warehouse_id', -1);  //仓库
        $category_id = $request->post('category_id', -1);  //分类
        $orderBy_field = $request->post('orderBy_field', 'stock');  //排序字段
        $orderBy_how = $request->post('orderBy_how', 'DESC');  //排序方式
        $page = $request->post('page', 1);
        $take = $request->post('take', 20);
        $warehouseIds = array_column($this->warehouses()['data']->toArray(), 'id');
        if ($warehouse_id > -1 && !in_array($warehouse_id, $warehouseIds)) {
            abort(422, '无效仓库');
        }

        $data = WarehouseMaterialModel::with('material')->when($keywords, function ($query) use ($keywords) {
            $query->where(function ($query) use ($keywords) {
                $query->where('material_code', 'like', '%' . $keywords . '%')->orWhere('material_name', 'like', '%' . $keywords . '%')->orWhere('material_alias_one', 'like', '%' . $keywords . '%');
            });
        })->when($warehouse_id > -1, function ($query) use ($warehouse_id) {
            $query->where('warehouse_id', $warehouse_id);
        }, function ($query) use ($warehouseIds) {
            $query->whereIn('warehouse_id', $warehouseIds);
        })->when($category_id > -1, function ($query) use ($category_id) {
            $query->where('material_category_id', $category_id);
        })->orderBy($orderBy_field, $orderBy_how)->skip(($page - 1) * $take)->take($take)->get()->map(function ($item) {
            return ['id' => $item->id, 'material_id' => $item->material_id, 'material_img' => $item->material->material_img, 'material_name' => $item->material_name, 'material_alias_one' => $item->material_alias_one, 'material_code' => $item->material_code, 'material_category_name' => $item->material_category_name, 'unit_name' => $item->unit_name, 'specifications' => $item->specifications, 'stock' => $item->stock];
        });

        return $this->return_data([
            'total_num' => $data->sum('stock'),
            'total_price' => 100,
            'data' => $data,
            'page' => $page
        ]);
    }

    //材料列表
    public function materials_list(Request $request)
    {
        $materials_name = $request->post('materials_name');
        $materials_code = $request->post('materials_code');
        $seacher_title = $request->post('keywords');
        $page = $request->post('page', 1);
        $take = $request->post('take', 20);

        $data = MaterialModel::when($seacher_title, function ($query) use ($seacher_title) {
            $query->orWhere('material_name', 'like', '%' . $seacher_title . '%')->orWhere('material_code', 'like', '%' . $seacher_title . '%');
        })->when($materials_name, function ($query) use ($materials_name) {
            $query->where(function ($query) use ($materials_name) {
                $query->where('material_name', 'like', '%' . $materials_name . '%');
            });
        })->when($materials_code, function ($query) use ($materials_code) {
            $query->where(function ($query) use ($materials_code) {
                $query->where('material_code', 'like', '%' . $materials_code . '%');
            });
        })->orderBy('created_at', 'desc')->skip(($page - 1) * $take)->take($take)->get();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    //材料详情
    public function material(MaterialModel $material)
    {
        $warehouseIds = array_column($this->warehouses()['data']->toArray(), 'id');

        return $this->return_data([
            'base' => [
                'id' => $material->id,
                'material_img' => $material->material_img,
                'material_name' => $material->material_name,
                'material_alias_one' => $material->material_alias_one,
                'material_alias_two' => $material->material_alias_two,
                'material_alias_three' => $material->material_alias_three,
                'material_code' => $material->material_code,
                'material_category_name' => $material->material_category_name,
                'unit_name' => $material->unit_name,
                'specifications' => $material->specifications,
                'warehouse_specifications' => WarehouseMaterialModel::where('material_id', $material->id)->whereIn('warehouse_id', $warehouseIds)->get()->map(function ($item) {
                    return ['warehouse_name' => $item->warehouse_name, 'stock' => $item->stock];
                })
            ],
            'inquiry_logs' => MaterialInquiryModel::where('material_id', $material->id)->get()->map(function ($item) {
                return ['inquiry_time' => $item->inquiry_time, 'admin_name' => $item->admin_name, 'supplier_name' => $item->supplier_name, 'manufacturer' => $item->manufacturer, 'brand' => $item->brand, 'invoice_name' => $item->invoice_name, 'supplier_offer' => $item->supplier_offer];
            }),
            'in_logs' => [],    //TODO:入库记录
            'out_logs' => [],   //TODO:出库记录
        ]);
    }

    //材料详情
    public function materials_detail(Request $request){
        $ids = $request->post('ids');
        $type = $request->post('type',1);
        if(empty($ids)){
            return response()->json(['code'=>'201','msg' => '参数错误']);
        }
        $id_array = json_decode($ids,true);
        if($type == 2){
            $list = MaterialModel::whereIn('id',$id_array)->get();
            foreach($list as $key=>$val){
                $warehouse_list = WarehouseMaterialModel::whereIn('material_id',$id_array)->first();
                $list[$key]['stock'] = empty($warehouse_list['stock'])?0:$warehouse_list['stock'];
            }
        }else{
            $list = WarehouseMaterialModel::whereIn('id',$id_array)->get();
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$list]);

    }

    //出库入库记录
    public function inout_record(Request $request){

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $seacher_title = $request->post('seacher_title');

        $warehouse_id = $request->post('warehouse_id');

        $material_code = $request->post('material_code');

        $material_id = $request->post('material_id');

        $warehouse_type = $request->post('warehouse_type');

        $start_time = $request->post('start_time');

        $end_time = $request->post('end_time');

        $data = WarehouseMaterialRecordModel::when($seacher_title,function($query,$seacher_title){
            return  $query->orwhere('code','like','%'.$seacher_title.'%')->orwhere('material_code','like','%'.$seacher_title.'%')->orwhere('material_name','like','%'.$seacher_title.'%')->orwhere('producer_name','like','%'.$seacher_title.'%');
        })->when($material_code,function($query,$material_code){
            return  $query->where('material_code',$material_code);
        })->when($material_id,function($query,$material_id){
            return  $query->where('material_id',$material_id);
        })->when($warehouse_type,function($query,$warehouse_type){
            return  $query->where('warehouse_type',$warehouse_type);
        })->when($warehouse_id,function($query,$warehouse_id){
            return  $query->where('warehouse_id',$warehouse_id);
        })->when($start_time,function($query,$start_time){
            return  $query->where('created_at','>=',date('Y-m-d H:i:s',$start_time));
        })->when($end_time,function($query,$end_time){
            return  $query->where('created_at','<',date('Y-m-d H:i:s',$end_time));
        })->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

}
